package com.syb.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.syb.dao.ResourcesDao;
import com.syb.entity.function.SysResource;
import com.syb.util.BaseDao;
import com.syb.util.PageResults;

@Repository
public class ResourcesDaoImpl extends BaseDao implements ResourcesDao {

	@Override
	public List<SysResource> findResourcesList(PageResults<SysResource> page) throws Exception {
		StringBuffer sub = new StringBuffer();
		List<Object> paramList = new ArrayList<Object>(); 
		List<SysResource> result = new ArrayList<SysResource>();
		sub.append(" from SysResource where 1=1");
		if(page.getParamMap().get("name")!=null && !("").equals(page.getParamMap().get("name"))){
			sub.append(" and resource_name like ? ");
			paramList.add("%"+page.getParamMap().get("name")+"%");
		}
		/*sub.append(" limit ?,? ");*/
		/*paramList.add(page.getCurrentPage());
		paramList.add(page.getPageSize());*/
		try{
		Query query = this.getSessionFactory().getCurrentSession().createQuery(sub.toString());
		query.setFirstResult(page.getCurrentPage());
		query.setMaxResults(page.getPageSize());
		if(paramList.size()>0){
			for(int i=0;i<paramList.size();i++){
				query.setParameter(i, paramList.get(i));
			}
		}
		result = query.list();
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
		return result;
	}

	@Override
	public int findResourcesCount(PageResults<SysResource> page) throws Exception {
		StringBuffer sub = new StringBuffer();
		List<Object> paramList = new ArrayList<Object>(); 
		List<BigInteger> result = new ArrayList<BigInteger>();
		sub.append("select count(*)  from sys_resource where 1=1");
		if(page.getParamMap().get("name")!=null && !("").equals(page.getParamMap().get("name"))){
			sub.append(" and resource_name like ? ");
			paramList.add("%"+page.getParamMap().get("name")+"%");
		}
		try{
		Query query = this.getSessionFactory().getCurrentSession().createSQLQuery(sub.toString());
		if(paramList.size()>0){
			for(int i=0;i<paramList.size();i++){
				query.setParameter(i, paramList.get(i));
			}
		}
		result = query.list();
		}catch(Exception e){
			throw new Exception(e.getMessage());
		}
		return result.get(0).intValue();
	}

}
